import url from 'url';
import router from 'koa-router';
import DBConnectTool from '../com/DBTool/DBConnectTool';
import ContentTypeTool from '../lib/ContentTypeTool';
import readFromNet from '../lib/GISServer/Util/readFromNet';
import path from 'path';
import configTool from '../com/configTool';
import imgMD5 from "../img/imgMD5";

const DBRoutes = new router({prefix: '/DBService'});

// 通配符的写法
DBRoutes
    .get('/ue_layer/(.*)', async (ctx: any) => {
        let reqUrl = ctx.request.url.replace('/DBService/ue_layer', '');
        let urlObj = url.parse(reqUrl, true) as any;
        reqUrl = decodeURI(urlObj.pathname);

        const regex = /\/(\d+)\/(\d+)\/(\d+)\.(jpg|jpeg|png)$/;
        if (regex.test(reqUrl)) {

            const match = reqUrl.match(regex);
            // 提取z、x、y的值
            const z = parseInt(match[1], 10);
            const x = parseInt(match[2], 10);
            const y = parseInt(match[3], 10);
            const realY = Math.pow(2, z) - y - 1;

            reqUrl = reqUrl.replace(regex, `/${z}/${x}/${realY}.$4`);
        }

        reqUrl = encodeURI(`http://127.0.0.1:${configTool.baseConfig.httpServerPort}/DBService` + reqUrl);
        console.log('UE规则代理接口：', decodeURI(reqUrl));
        const res = await readFromNet({url: reqUrl});

        let contentType = ContentTypeTool.getContentType(path.basename(reqUrl));
        ctx.set('content-type', contentType);
        ctx.body = res[1];
    })
    .get('/(.*)', async (ctx: any) => {
        let reqUrl = ctx.request.url.replace('/DBService/', '');
        let urlObj = url.parse(reqUrl, true) as any;
        reqUrl = decodeURI(urlObj.pathname);


        let pathItem = reqUrl.split('/');

        if (pathItem?.length) {
            let DBName = pathItem.shift();
            let fullPath = '/' + pathItem.join('/');

            let file;
            let dbTool = await DBConnectTool.openDB(DBName);

            if (dbTool) {
                if (DBName.endsWith('-Index')) {
                    const indexDB = await DBConnectTool.openDB(DBName);
                    const indexInfo = await indexDB.getFileByFullPath(fullPath, false);
                    const md5 = indexInfo?.file_md5;
                    if (md5) {
                        const dataDBName = DBName.endsWith('-16x16-Index') ? DBName.replace('-16x16-Index', '-') : DBName.replace('-Index', '-');
                        const dbTool = await DBConnectTool.openDB(dataDBName + md5.substring(0, DBName.endsWith('-16x16-Index') ? 2 : 1));
                        file = await dbTool.getFileByFullPath(fullPath, false);
                    }
                } else {
                    file = await dbTool.getFileByFullPath(fullPath, false);
                }

                if (!file || !file.file_data) {
                    const lowReqUrl = reqUrl.toLowerCase();
                    if (lowReqUrl.endsWith('.png') || lowReqUrl.endsWith('.jpg') || lowReqUrl.endsWith('.jpeg') || lowReqUrl.endsWith('.webp')) {
                        ctx.status = 200;
                        ctx.body = imgMD5.transparentBuffer;
                    } else {
                        ctx.status = 422;
                        ctx.set('content-type', 'application/json;charset=utf-8');
                        ctx.body = JSON.stringify({message: `资源库【${DBName}】连接成功，但找不到该文件资源，路径：【${fullPath}】`});
                    }
                } else {
                    let contentType = ContentTypeTool.getContentType(file.file_name);
                    file.file_zip === 'gzip' && (ctx.set('Content-Encoding', 'gzip'));
                    ctx.set('content-type', contentType);
                    ctx.body = file.file_data;
                }
            } else {
                ctx.status = 422;
                ctx.set('content-type', 'application/json;charset=utf-8');
                ctx.body = JSON.stringify({message: `资源库不存在【${DBName}】，请检查 Url`});
                return;
            }
        }
    })
;


export default DBRoutes;
